import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import renderModal, {
    getModelValue,
    initModelValue,
    type FormModalDto
} from '@/components/modal/Modal'
import toNative from '@/utils/toNative'
import { message, type RadioChangeEvent } from 'ant-design-vue'
import { ButtonMenuTypeCnEnum, getKeyToEnum, PlatformTypeCnEnum } from '@/const/enum'
import { addMenu, editMenu, getMenuList } from '@/api/system'
import type { MenuDto } from '@/api/system/types'
import type { OptionDto } from '@/components/low-code/types'
import type { AddType } from '@/api/types'

@Component
export class DialogAddMenu extends Render {
    @Prop({ default: false }) show!: boolean
    @Prop() addType!: AddType
    @Prop() menuData!: MenuDto

    @Emit('update:show')
    showChange(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('show', { immediate: true })
    async handleWatchShow() {
        this.formConfig.show = this.show
        if (this.show) {
            await this.initTreeData()
            console.log(111, this.menuData)
            this.formConfig.title = this.addType === 'edit' ? '编辑菜单' : '添加菜单'
            switch(this.addType) {
            case 'newAdd':
                initModelValue(this.formConfig)
                break
            case 'add':
                initModelValue(this.formConfig, { 
                    parentId: this.menuData?.menuId ?? '0',
                    platform: this.menuData?.platform ?? undefined
                })
                break
            case 'edit':
                initModelValue(this.formConfig, this.menuData)
                break
            default:
                initModelValue(this.formConfig)
            }
            this.setVisible()
        }
    }

    formConfig = this.initFormConfig() as FormModalDto

    menuPropList = {
        M: [
            'parentId',
            'menuType',
            'icon',
            'menuName',
            'orderNum',
            'remark',
            'isFrame',
            'path',
            'visible',
            'titleList',
            'isShowCrumb',
            'status',
            'platform'
        ],
        C: [
            'parentId',
            'menuType',
            'icon',
            'menuName',
            'orderNum',
            'remark',
            'isFrame',
            'path',
            'component',
            'perms',
            'visible',
            'titleList',
            'isShowCrumb',
            'status',
            'isCache',
            'platform'
        ],
        F: ['parentId', 'menuType', 'menuName', 'orderNum', 'remark', 'path', 'btnEvent', 'perms', 'btnPosition', 'btnStyle', 'platform']
    }

    initFormConfig() {
        return {
            title: '添加菜单',
            width: '650px',
            theme: 'dark',
            show: false,
            items: {
                parentId: {
                    name: '上级菜单',
                    element: 'treeSelect',
                    defaultValue: '0',
                    required: true,
                    params: {

                    }
                },
                menuType: {
                    name: '菜单类型',
                    element: 'radioGroup',
                    defaultValue: 'M',
                    options: [
                        {
                            label: '目录',
                            value: 'M'
                        },
                        {
                            label: '菜单',
                            value: 'C'
                        },
                        {
                            label: '按钮',
                            value: 'F'
                        }
                    ],
                    callback: {
                        change: (ev: RadioChangeEvent) => {
                            console.log(111, ev)
                            this.setVisible()
                        }
                    }
                },
                // icon: {
                //     name: '菜单图标',
                //     element: 'selectMenu',
                // },
                menuName: {
                    name: '菜单名称',
                    element: 'input',
                    span: 12,
                    required: true
                },
                orderNum: {
                    name: '显示排序',
                    element: 'inputNumber',
                    span: 12,
                    required: true
                },
                isFrame: {
                    name: '是否外链',
                    element: 'radioGroup',
                    span: 12,
                    defaultValue: '1',
                    options: [
                        {
                            label: '是',
                            value: '0'
                        },
                        {
                            label: '否',
                            value: '1'
                        }
                    ]
                },
                path: {
                    name: '路由地址',
                    element: 'input',
                    span: 12
                },
                btnEvent: {
                    name: '按钮事件',
                    element: 'input',
                    span: 12
                },
                remark: {
                    name: '备注',
                    element: 'input',
                    span: 12
                },
                perms: {
                    name: '权限标识',
                    element: 'input',
                    span: 12,
                    hidden: true
                },
                btnPosition: {
                    name: '按钮位置',
                    element: 'select',
                    options: getKeyToEnum(ButtonMenuTypeCnEnum),
                    span: 12,
                    hidden: true
                },
                btnStyle: {
                    name: '按钮样式',
                    element: 'input',
                    span: 12,
                    hidden: true
                },
                visible: {
                    name: '显示状态',
                    element: 'radioGroup',
                    defaultValue: '0',
                    span: 12,
                    options: [
                        {
                            label: '显示',
                            value: '0'
                        },
                        {
                            label: '隐藏',
                            value: '1'
                        }
                    ]
                },
                // titleList: {
                //     name: '面包屑',
                //     element: 'input',
                //     span: 12,
                //     hidden: true
                // },
                // isShowCrumb: {
                //     name: '面包屑显示',
                //     element: 'radioGroup',
                //     span: 12,
                //     options: [
                //         {
                //             label: '显示',
                //             value: '0'
                //         },
                //         {
                //             label: '不显示',
                //             value: '1'
                //         }
                //     ]
                // },
                status: {
                    name: '菜单状态',
                    element: 'radioGroup',
                    span: 12,
                    defaultValue: '0',
                    options: [
                        {
                            label: '正常',
                            value: '0'
                        },
                        {
                            label: '停用',
                            value: '1'
                        }
                    ]
                },
                isCache: {
                    name: '是否缓存',
                    element: 'radioGroup',
                    span: 12,
                    options: [
                        {
                            label: '缓存',
                            value: '0'
                        },
                        {
                            label: '不缓存',
                            value: '1'
                        }
                    ],
                    hidden: true
                },
                platform: {
                    name: '平台',
                    element: 'radioGroup',
                    required: true,
                    options: getKeyToEnum(PlatformTypeCnEnum)
                }
            },
            complete: async () => {
                const data = getModelValue(this.formConfig, true)

                if (this.addType === 'add' || this.addType === 'newAdd') {
                    await addMenu(data)
                } else {
                    const params = Object.assign(this.menuData as MenuDto, data)
                    await editMenu(params)
                }
                message.success('操作成功')
                this.handleRefresh()
                this.formConfig.show = false
                this.showChange(false)
            },
            cancel: () => {
                this.formConfig.show = false
                this.showChange(false)
            },
            init: () => {
                // initModelValue(this.formConfig)
            }
        } as FormModalDto
    }

    setVisible() {
        const data = getModelValue(this.formConfig)
        const items = this.formConfig.items
        for (const key in items) {
            const menuPropList = this.menuPropList[data.menuType as keyof typeof this.menuPropList]
            items[key].hidden = menuPropList.every((i) => i !== key)
        }
        const menuMap = {
            'M': '目录',
            'C': '菜单',
            'F': '按钮'
        }
        items.menuName.name = `${menuMap[data.menuType as keyof typeof menuMap]}名称` 
    }

    async initTreeData() {
        const res = (await getMenuList({})).map(i => {
            return {
                ...i,
                label: i.menuName,
                value: i.menuId
            }
        })
        const menu = [{ value: '0', label: '主类目', children: [] as MenuDto[] }] as OptionDto[]
        menu[0].children = this.handleTree(res, 'menuId')

        // initModelValue(this.formConfig, {
        //     parentId: menu
        // })
        // console.log(123, menu)
        this.formConfig.items.parentId.options = menu

        // console.log(1000, this.formConfig.items.parentId)
    }

    /**
     * 构造树型结构数据
     * @param {*} data 数据源
     * @param {*} id id字段 默认 'id'
     * @param {*} parentId 父节点字段 默认 'parentId'
     * @param {*} children 孩子节点字段 默认 'children'
     * @param {*} rootId 根Id 默认 0
     */
    handleTree(
        data: MenuDto[],
        id: string = 'id',
        parentId: string = 'parentId',
        children: string = 'children',
        rootId: number = 0
    ) {
        // id = id || 'id'
        // parentId = parentId || 'parentId'
        // children = children || 'children'
        rootId =
            rootId ||
            // eslint-disable-next-line prefer-spread
            Math.min.apply(
                Math,
                data.map((item) => {
                    return item[parentId as keyof typeof item] as number
                })
            ) ||
            0
        //对源数据深度克隆
        const cloneData = JSON.parse(JSON.stringify(data)) as MenuDto[]
        //循环所有项
        const treeData = cloneData.filter((father) => {
            const branchArr = cloneData.filter((child) => {
                //返回每一项的子级数组
                return father[id as keyof typeof father] === child[parentId as keyof typeof child]
            })
            branchArr.length > 0 ? (father.children = branchArr) : ''
            //返回第一层
            return father[parentId as keyof typeof father] === rootId
        })
        return treeData//treeData !== '' ? treeData : data
    }

    render() {
        return <div>{renderModal(this.formConfig)}</div>
    }
}

export default toNative<{ addType: AddType, menuData: MenuDto }, { refresh: () => void }>(DialogAddMenu)
